package com.andy.module.progress

import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.BufferedSource
import okio.Okio
import okio.buffer

/**
 * @creator:LuoFan
 * @date:2022/6/9
 * @description:
 */
class ProgressResponseBody(private val body: ResponseBody, private val progressListener: ProgressListener?) : ResponseBody() {

    //刷新进度间隔
    var refreshTime = 200

    private lateinit var progressSource: BufferedSource

    override fun contentType(): MediaType? {
        return body.contentType()
    }

    override fun contentLength(): Long {
        return body.contentLength()
    }

    override fun source(): BufferedSource {
        if (progressListener == null) {
            return body.source()
        }
        val source = ProgressSource(body.source(), body.contentLength(), progressListener)
        source.refreshTime = refreshTime
        progressSource = source.buffer()
        return progressSource
    }

    override fun close() {
        try {
            progressSource.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}